package com.caine.multithread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: CaineZhu
 * @Description: 这种在多线程下依旧是有bug的
 * @Date: Created in 17:07 2020/12/10
 * @Modified By:
 */
public class ConditionDemo3 {
    static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(2);
        String[] char1 = {"1","2","3","4","5"};
        String[] char2 = {"11","12","13","14","15"};
        String[] char3 = {"21","22","23","24","25"};

        Condition condition1 = lock.newCondition();
        Condition condition2 = lock.newCondition();
        Condition condition3 = lock.newCondition();

        new Thread(() -> {
            latch.countDown();
            lock.lock();
            try {
                for (String c : char1) {
                    System.out.print(c);
                    System.out.print(" ");
                    condition2.signal();
                    condition1.await();
//                    condition3.await();
                }
                condition2.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t1").start();

        new Thread(() -> {
            latch.countDown();
            lock.lock();
            try {
                for (String c : char2) {
                    System.out.print(c);
                    System.out.print(" ");
                    condition3.signal();
//                    condition1.await();
                    condition2.await();
                }
                condition3.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t2").start();

        new Thread(() -> {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.lock();
            try {
                for (String c : char3) {
                    System.out.print(c);
                    System.out.print(" ");
                    condition1.signal();
//                    condition2.await();
                    condition3.await();
                }
                condition1.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t3").start();
    }
}
